package cn.bone.netty3.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Created by superbone on 2016/9/22.
 */
public class EchoServer {

    public static void main(String[] args) throws Exception {
        new EchoServer().bind();
    }

    public void bind() throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,100)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    //添加处理的handler
                    .childHandler(new ServerChildhandler());

            //绑定端口,同步等待成功
            ChannelFuture f = b.bind(8000).sync();
            //等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        }finally {
            //退出,释放资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

class ServerChildhandler extends ChannelInitializer<SocketChannel>{

    protected void initChannel(SocketChannel ch) throws Exception {

        //使用$_作为分隔符的自定义分隔符解码器
        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));

        //ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
        ch.pipeline().addLast(new StringDecoder());
        //在管道中添加我们自己的接收数据实现方法
        ch.pipeline().addLast(new EchoServerHandler());
    }
}

class EchoServerHandler extends ChannelHandlerAdapter{
    int counter = 0;

    //读取消息处理方法
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        String body = (String)msg;
        System.out.println("第"+(++counter)+"次收到的消息是:"+body);
        String responseStr = "服务端响应消息"+body+"$_";
        ByteBuf echo = Unpooled.copiedBuffer(responseStr.getBytes("UTF-8"));
        ctx.writeAndFlush(echo);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("服务端发生异常!");
        System.out.println(cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }
}
